#include "ctrlreport.h"

CtrlReport::CtrlReport(QObject *parent) : QObject(parent)
{
    address = QString();
    manager = new QNetworkAccessManager(this);
    curReport = QString();
    reportDir = QDir(qApp->applicationDirPath() + "/report/");
    repFlag = 0;
    curInfo = NULL;
    reportReply = NULL;
    taskTimer = new QTimer(this);
    connect(taskTimer, SIGNAL(timeout()), this, SLOT(taskclearTimeout()));
    taskTimer->start(3600000);
    taskclearTimeout();
}

void CtrlReport::setServerAddress(QString addr)
{
    address = addr;
}

QString CtrlReport::xmlReport(ctrlInfo *info)
{
//    return QString("<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ser=\"http://service.monitor.spdservice.lantosec.com/\"><soapenv:Header/><soapenv:Body><ser:saveBarCodeForIntelligentCabinetService><!--Optional:--><bcic><!--Optional:--><cabinetNumber>%1</cabinetNumber><!--Optional:--><caseNbr>%2</caseNbr><!--Optional:--><comDepotCode>%3</comDepotCode><!--Optional:--><comDepotName>%4</comDepotName><!--Optional:--><dateCd>%5</dateCd><!--Optional:--><goodsDesc>%6</goodsDesc><!--Optional:--><goodsName>%7</goodsName><!--Optional:--><goodsOpcode>%8</goodsOpcode><!--Optional:--><goodsRegistration>%9</goodsRegistration><!--Optional:--><num>?</num><!--Optional:--><productLocation>%10</productLocation><!--Optional:--><timeConsuming>%11</timeConsuming><!--Optional:--><userCode>%12</userCode><!--Optional:--><userName>%13</userName></bcic></ser:saveBarCodeForIntelligentCabinetService></soapenv:Body></soapenv:Envelope>").arg(info->cabinetNumber).arg(info->caseNbr).arg(info->comDepotCode).arg(info->comDepotName).arg(info->timeConsuming).arg(info->goodsDesc).arg(info->goodsName).arg(info->goodsRegistration).arg(info->num).arg(info->productLocation).arg(info->timeConsuming).arg(info->userCode).arg(info->userName).toLocal8Bit();
    QString repName = qApp->applicationDirPath() + "/report/" + info->timeConsuming.toString("yyyyMMddhhmmsszzz")+".xml";
    QDir dir(qApp->applicationDirPath() + "/report/");
    if(!dir.exists())
        dir.mkdir(qApp->applicationDirPath() + "/report/");

    QFile f(repName);
    if(!f.open(QFile::WriteOnly))
        return QByteArray();
    info->unicodeTrans();
    QString strXml = QString("<?xml version=\"1.0\" encoding=\"UTF-8\"?><soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ser=\"http://service.monitor.spdservice.lantosec.com/\"><soapenv:Header/><soapenv:Body><ser:saveBarCodeForIntelligentCabinetService><!--Optional:--><bcic><!--Optional:--><cabinetNumber>%1</cabinetNumber><!--Optional:--><caseNbr>%2</caseNbr><!--Optional:--><comDepotCode>%3</comDepotCode><!--Optional:--><comDepotName>%4</comDepotName><!--Optional:--><goodsDesc>%5</goodsDesc><!--Optional:--><goodsName>%6</goodsName><!--Optional:--><goodsOpcode>%7</goodsOpcode><!--Optional:--><goodsRegistration>%8</goodsRegistration><!--Optional:--><num>%9</num><!--Optional:--><productLocation>%10</productLocation><!--Optional:--><timeConsuming>%11</timeConsuming><!--Optional:--><userCode>%12</userCode><!--Optional:--><userName>%13</userName><goodsUnitPrice>%14</goodsUnitPrice><goodsSumMoney>%15</goodsSumMoney></bcic></ser:saveBarCodeForIntelligentCabinetService></soapenv:Body></soapenv:Envelope>").arg(info->cabinetNumber).arg(info->caseNbr).arg(info->comDepotCode).arg(info->comDepotName).arg(info->goodsDesc).arg(info->goodsName).arg(info->goodsOpcode).arg(info->goodsRegistration).arg(info->num).arg(info->productLocation).arg(info->timeConsuming.toString("yyyy-MM-dd hh:mm:ss")).arg(info->userCode).arg(info->userName).arg(info->goodsUnitPrice).arg(info->goodsSumMoney);
    QByteArray src = strXml.toUtf8();
    QByteArray sign = QCryptographicHash::hash(src+QByteArray("hnrmxx")+f.fileName().toLocal8Bit(), QCryptographicHash::Md5);
    qDebug()<<sign.size();
    f.write(sign);
    f.write(src);
    f.close();
    return repName;

    //unuse

    info->unicodeTrans();
    QXmlStreamWriter writer(&f);
    writer.setAutoFormatting(true);
    writer.setCodec("utf-8");
    writer.writeStartElement("soapenv:Envelope");
    QXmlStreamAttributes attributes;
    attributes.append("xmlns:soapenv", "http://schemas.xmlsoap.org/soap/envelope/");
    attributes.append("xmlns:ser", "http://service.monitor.spdservice.lantosec.com/");
    writer.writeAttributes(attributes);
    writer.writeStartElement("soapenv:Header");
    writer.writeStartElement("soapenv:Body");
    writer.writeStartElement("ser:saveBarCodeForIntelligentCabinetService");
    writer.writeStartElement("bcic");
    writer.writeTextElement("cabinetNumber", info->cabinetNumber);
    writer.writeTextElement("caseNbr", info->caseNbr);
    writer.writeTextElement("comDepotCode", info->comDepotCode);
    writer.writeTextElement("comDepotName", info->comDepotName);
    writer.writeTextElement("goodsDesc", info->goodsDesc);
    writer.writeTextElement("goodsName", info->goodsName);
    writer.writeTextElement("goodsOpcode", info->goodsOpcode);
    writer.writeTextElement("goodsRegistration", info->goodsRegistration);
    writer.writeTextElement("num", info->num);
    writer.writeTextElement("productLocation", info->productLocation);
    writer.writeTextElement("timeConsuming", info->timeConsuming.toString("yyyy-MM-dd hh:mm:ss"));
    writer.writeTextElement("userCode", info->userCode);
    writer.writeTextElement("userName", info->userName);
    writer.writeEndElement();
    writer.writeEndElement();
    writer.writeEndElement();
    writer.writeEndElement();
    writer.writeEndElement();
    writer.writeEndDocument();
    f.close();

    if(!f.open(QFile::ReadOnly))
        return QByteArray();
    QByteArray qba = f.readAll();
//    qDebug()<<strXml;
//    qDebug()<<qba;
    return qba;
}

QString CtrlReport::utf8ToUnicode(QString utf)
{
    QString strout;

    for (int i=0; i<utf.length(); ++i)
    {
        ushort num = utf[i].unicode();
        if (num < 255)
            strout += "00";

        strout += QString::number(num,16);
    }
    return strout;
}

void CtrlReport::sendReport(QString reportFile)
{
    if(reportFile.isEmpty())
        return;
//    QFile f(repName);
//    if(!f.open(QFile::ReadOnly))
//        return;

    ReportTask* task = new ReportTask(manager, address,reportFile);
    connect(task, SIGNAL(reportRst(bool)), this, SIGNAL(reportRst(bool)));
    task->taskStart();
}

void CtrlReport::newReport(ctrlInfo *info)
{
    QString rep = xmlReport(info);
    sendReport(rep);
}

void CtrlReport::recv_goods_report()
{
    QByteArray qba = reportReply->readAll();
    qDebug()<<QString(qba);
    QString curTime = QString("Fri, 12 Oct 2018 01:28:28 GMT");//QString(reportReply->rawHeader("Date"));
    QDateTime serverTime = QDateTime::fromString(curTime ,"ddd, dd MMM yyyy hh:mm:ss");
//    serverTime.setTimeSpec(Qt::UTC);
    qDebug()<<"curTime:"<<curTime;
    qDebug()<<serverTime.toString();
    QString(reportReply->rawHeader("Date"));
    reportReply->deleteLater();
    reportReply = NULL;
}

void CtrlReport::taskclearTimeout()
{
    qDebug()<<"[task clear]";
    QStringList filter;
    filter<<"*.xml";
    fileList = reportDir.entryList(filter, QDir::NoDotAndDotDot|QDir::Files|QDir::Readable, QDir::Name);
    if(!fileList.isEmpty())
    {
        QTimer::singleShot(5000, this, SLOT(nextTaskTimeout()));
    }
}

void CtrlReport::nextTaskTimeout()
{
    QString file = fileList.takeFirst();
    sendReport(reportDir.absoluteFilePath(file));
    if(!fileList.isEmpty())
    {
        QTimer::singleShot(5000, this, SLOT(nextTaskTimeout()));
    }
}


